import React from 'react'
import {connect} from 'react-redux'
import { Form, Select, message, Button } from 'antd';
import {messages} from "share/common";
import interfaceService from "containers/financial-account/interface-definition/interface-service";
import Chooser from "components/chooser";
import ChooseInput from "containers/financial-account/template/choose-input";
import config from "config";
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class mappingRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      saveLoading: false,
      functionDefineId: '',
      functionSourceGroupId: '',
      functionSegmentId: '',
      childNodes: []
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      this.setState({
        functionDefineId: '',
        functionSourceGroupId: '',
        functionSegmentId: '',
        childNodes: []
      });
      return !1;
    }
    this.props.form.resetFields();
  }

  handleNodesOK = value => {
    this.setState({ functionSegmentId: value.id });
  };

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        const { user, elementDefinition } = this.props;
        const { functionSegmentId, functionDefineId, functionSourceGroupId } = this.state;
        this.setState({saveLoading: true});
        let temp = {
          sceneElementId: elementDefinition.id,
          functionSegmentId,
          functionDefineId,
          functionSourceGroupId,
          isDefault: values.isDefault
        };
        interfaceService.addMapping(temp,user.userOID).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(e.response.data.message);
        })
      }
    })
  };

  render(){
    const { saveLoading, functionDefineId, functionSourceGroupId, childNodes } = this.state;
    const { businessInterface } = this.props;
    const { getFieldDecorator } = this.props.form;
    return(
      <div>
        <Form style={{marginTop:'10px'}}>
          <FormItem label={messages('financial-account.key100')/*核算业务定义编码*/} {...formItemLayout}>
            {getFieldDecorator('functionDefineId', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
            })(
              <Chooser selectorItem={{
                        title: messages('financial-account.key144')/*选择核算业务定义编码*/,
                        url: `${config.baseUrl}/ledger/api/functionDef/query/by/page`,
                        searchForm: [{
                          type: 'input',
                          id: 'typeCode',
                          label: messages('financial-account.key52')/*核算业务类型编码*/
                        },{
                          type: 'input',
                          id: 'typeName',
                          label: messages('financial-account.key53')/*核算业务类型名称*/
                        }],
                        columns: [
                          {title: messages('financial-account.key100')/*核算业务定义编码*/, dataIndex: 'typeCode'},
                          {title: messages('financial-account.key101')/*核算业务定义名称*/, dataIndex: 'typeName'}
                        ],
                        key: 'id',
                        listKey: "rows"
                       }}
                       valueKey="id"
                       onChange={value => {
                         this.setState({functionDefineId: value[0] ? value[0].id : '', functionSourceGroupId: '', functionSegmentId: ''},() => {
                           this.props.form.setFieldsValue({ functionSourceGroupId: undefined, functionSegmentId: undefined });
                         });
                       }}
                       listExtraParams={{functionId: businessInterface.id}}
                       labelKey="typeCode"
                       single/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key63')/*来源数据编码*/} {...formItemLayout}>
            {getFieldDecorator('functionSourceGroupId', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
            })(
              <Chooser selectorItem={{
                         title: messages('financial-account.key145')/*选择来源数据编码*/,
                         url: `${config.baseUrl}/ledger/api/function/source/group/query/by/page`,
                         searchForm: [],
                         columns: [
                           {title: messages('financial-account.key63')/*来源数据编码*/, dataIndex: 'detailSourceCode'},
                           {title: messages('financial-account.key64')/*来源数据名称*/, dataIndex: 'detailSourceName'}
                         ],
                         key: 'id',
                         listKey: "rows"
                       }}
                       onChange={value => {
                         this.setState({functionSourceGroupId: value[0] ? value[0].id : '', functionSegmentId: ''},() => {
                           this.props.form.setFieldsValue({ functionSegmentId: undefined });
                         });
                       }}
                       valueKey="id"
                       disabled={functionDefineId.length === 0}
                       listExtraParams={{functionDefineId: functionDefineId}}
                       labelKey="detailSourceCode"
                       single/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key65')/*映射字段编码*/} {...formItemLayout}>
            {getFieldDecorator('functionSegmentId', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
            })(
              <Chooser selectorItem={{
                         title: messages('financial-account.key146')/*选择映射字段编码*/,
                         url: `${config.baseUrl}/ledger/api/function/segment/query/by/page`,
                         searchForm: [{
                           type: 'input',
                           id: 'detailSourceCodeOrName',
                           label: messages('financial-account.key147')/*映射字段编码/名称*/
                         }],
                         columns: [
                           {title: messages('financial-account.key65')/*映射字段编码*/, dataIndex: 'segmentCode'},
                           {title: messages('financial-account.key66')/*映射字段名称*/, dataIndex: 'segmentName'}
                         ],
                         key: 'id',
                         listKey: "rows"
                       }}
                       valueKey="id"
                       onChange={value => {
                         let temp = value[0] || {};
                         this.setState({ functionSegmentId: temp.id, childNodes: temp.childNodes });
                       }}
                       disabled={functionSourceGroupId.length === 0}
                       listExtraParams={{functionSourceGroupId: functionSourceGroupId}}
                       labelKey="segmentCode"
                       single/>
            )}
          </FormItem>
          {
            childNodes && childNodes.length > 0 && (
              <FormItem label={messages('financial-account.key188')/*扩展字段编码*/} {...formItemLayout}>
                {getFieldDecorator('expandedCode')(
                  <ChooseInput onOk={this.handleNodesOK} infoData={childNodes}/>
                )}
              </FormItem>
            )
          }
          <FormItem label={messages('financial-account.key5')/*是否预置*/} {...formItemLayout}>
            {getFieldDecorator('isDefault', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
              initialValue: 'false'
            })(
              <Select disabled>
                <Option key={'true'}>{messages('common.yes')/*是*/}</Option>
                <Option key={'false'}>{messages('common.no')/*否*/}</Option>
              </Select>
            )}
          </FormItem>
        </Form>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    elementDefinition: state.financialAccount.elementDefinition,
    user: state.login.user,
    businessInterface: state.financialAccount.businessInterface
  }
}

const wrappedMappingRule = Form.create()(mappingRule);
export default connect(mapStateToProps)(wrappedMappingRule);
